package org.qiyu.live.im.core.server.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-06
 * Time: 17:31
 */
public class NioSimpleServer {

    // 我们将接受到的socketChannel放到List集合中
    static List<SocketChannel> socketChannelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        // 创建socketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定9090端口
        serverSocketChannel.socket().bind(new InetSocketAddress(9090));
        serverSocketChannel.configureBlocking(false);//设置为非阻塞

        // 创建一个线程去执行List中的channel 读取数据
        new Thread(()->{
            for (SocketChannel socketChannel : socketChannelList) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(10);
                try {
                    socketChannel.read(byteBuffer);
                    System.out.println("服务端接收数据 :" + new String(byteBuffer.array()));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();

        while(true) {
            // 不断地接收客户端的连接
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(socketChannel != null) {
                System.out.println("服务器连接成功");
                socketChannel.configureBlocking(false);
                socketChannelList.add(socketChannel);
            }
        }
    }
}